assert(PandaDKPMaster, "PandaDKPMaster not found!")

------------------------------
--      Are you local?      --
------------------------------
local PandaDKPMaster = PandaDKPMaster
local Audit =
{
   UI = {},
}
PandaDKPMaster.Audit = Audit

local dewdrop = AceLibrary("Dewdrop-2.5")


function Audit:Enable()
   Audit:SetupUI()
end





----------------------
--   Interface UI   --
----------------------

function Audit:SetupUI()
   Audit.UI.SelectedPool = PandaDKPMaster.db.realm.DKP.Pools[1]
   local players = PandaDKPMaster.Players:AllPlayers()
   sort(players)
   Audit.UI.SelectedPlayer = players[1]
   
   PDKPM_AuditConfigPlayerMenuText:SetText(Audit.UI.SelectedPlayer)
   PDKPM_AuditConfigPlayerMenuButton:SetScript("OnClick",
    function()
      PandaDKPMaster.Audit:PlayerListClicked(PDKPM_AuditConfigPlayerMenu)
      PlaySound("igMainMenuOptionCheckBoxOn");
	 end)
   PDKPM_AuditConfigPoolMenuText:SetText(Audit.UI.SelectedPool)
   PDKPM_AuditConfigPoolMenuButton:SetScript("OnClick",
    function()
      PandaDKPMaster.Audit:PoolListClicked(PDKPM_AuditConfigPoolMenu)
      PlaySound("igMainMenuOptionCheckBoxOn");
	 end)


   Audit:RefilterAuditList()
   
   PDKPM_AuditConfigListTimestampHeaderTitle:SetText("Timestamp")
   PDKPM_AuditConfigListTimestampHeader.sorter = "ts"
   PDKPM_AuditConfigListDescriptionHeaderTitle:SetText("Description")
   PDKPM_AuditConfigListDescriptionHeader.sorter = "type"
   PDKPM_AuditConfigListDKPHeaderTitle:SetText("DKP")
   PDKPM_AuditConfigListDKPHeader.sorter = "dkp"
end

function Audit:PlayerListClicked(button)
   local options = { type = "group", args = {}, }
   local players = PandaDKPMaster.Players:AllPlayers()
   sort(players)
   
   for i, player in ipairs(players) do
      local class = PandaDKPMaster.Players:Class(player)
      local letter = strsub(player, 1, 1)
      if (nil == options.args[letter]) then
         local group = {
            type = 'group',
            name = letter,
            desc = letter,
            args = {},
         }
         options.args[letter] = group
      end
      
      local option =
      {
         type = 'execute',
         name = string.format("|cff%s%s|r ", PandaDKPMaster:getClassHex(class), player),
         desc = player,
         func = function(player) Audit:SelectPlayer(player) dewdrop:Close(); end,
         order = i,
         passValue = player,
      }
      tinsert(options.args[letter].args, option)
   end
   dewdrop:Open(button, 'children', options, 'point', "TOP", 'relativePoint', "BOTTOM")
end

function Audit:SelectPlayer(player)
   Audit.UI.SelectedPlayer = player
   PDKPM_AuditConfigPlayerMenuText:SetText(Audit.UI.SelectedPlayer)
   Audit:RefilterAuditList()
end

function Audit:PoolListClicked(button)
   local options = { type = "group", args = {}, }
   for i, pool in ipairs(PandaDKPMaster.db.realm.DKP.Pools) do
      local option =
      {
         type = 'execute',
         name = pool,
         desc = pool,
         func = function(pool) Audit:SelectPool(pool) dewdrop:Close(); end,
         order = i,
         passValue = pool,
      }
      tinsert(options.args, option)
   end
   dewdrop:Open(button, 'children', options, 'point', "TOP", 'relativePoint', "BOTTOM")
end

function Audit:SelectPool(pool)
   Audit.UI.SelectedPool = pool
   PDKPM_AuditConfigPoolMenuText:SetText(Audit.UI.SelectedPool)
   Audit:RefilterAuditList()
end

function Audit:HeaderOnClick(self, button)
end



function Audit:RefilterAuditList()
   Audit.UI.AuditList = {}
   
   local event =
   {
      type = '~~',
      ts = PandaDKPMaster:GetDatestamp(PandaDKPMaster:ThirtyDaysAgo()),
      dkp = PandaDKPMaster.Players:GetHistoricalDKP(Audit.UI.SelectedPlayer, Audit.UI.SelectedPool)
   }
   tinsert(Audit.UI.AuditList, event)
   
   local function EventFilter(event, data)
      if ("AW" == event.type and data.pool == event.pool) then
         for i, player in pairs(event.players) do
            if (player == data.player) then
               return true
            end
         end
      elseif ("PI" == event.type and data.pool == event.pool) then
         if (data.player == event.player) then
            return true
         end
      end
      
      return false
   end
   
   -- Find all events that match the filter
   local matches = PandaDKPMaster.Events:FindEvents(EventFilter, {player = Audit.UI.SelectedPlayer, pool = Audit.UI.SelectedPool})
   for i, md5 in pairs(matches) do
      tinsert(Audit.UI.AuditList, PandaDKPMaster.db.realm.DKP.Events[md5])
   end
   
   -- Sort the list according to timestamp
   local function SortList(a, b)
      return a.ts < b.ts
   end
   sort(Audit.UI.AuditList, SortList)
   
   -- Calculate the running total of DKP
   local total = 0
   for i=1, #(Audit.UI.AuditList) do
      if ("PI" == Audit.UI.AuditList[i].type) then
         total = total - Audit.UI.AuditList[i].dkp
      else
         total = total + Audit.UI.AuditList[i].dkp
      end
      Audit.UI.AuditList[i].total = total
   end
   
   Audit:AuditListUpdate()
end



function Audit:AuditListUpdate()
   local numEntries = #(Audit.UI.AuditList)
   FauxScrollFrame_Update(PDKPM_AuditConfigListScrollFrame, numEntries, 16, 16, nil, 350, 350, nil, 350, 350, true)
   
   local line
   local offset
   
   for line = 1, 16 do
      offset = line + FauxScrollFrame_GetOffset(PDKPM_AuditConfigListScrollFrame)
      local button = getglobal("PDKPM_AuditConfigListEventLine"..line)
      local event = Audit.UI.AuditList[offset]
      button:SetID(offset)
      if (offset <= numEntries) then
         local text = _G["PDKPM_AuditConfigListEventLine"..line.."Timestamp"]
         text:SetText(PandaDKPMaster:TimestampToTimeString(event.ts))
         
         text = _G["PDKPM_AuditConfigListEventLine"..line.."DKP"]
         text:SetText(string.format("%.2f", event.total))
         
         text = _G["PDKPM_AuditConfigListEventLine"..line.."Description"]
         if ("~~" == event.type) then
            text:SetText("Previous balance")
         elseif ("AW" == event.type) then
            text:SetText(string.format("Awarded %.2f for %s", event.dkp, event.notes))
         elseif ("PI" == event.type) then
            local _, itemLink = GetItemInfo(event.itemId)
            if (nil == itemLink) then itemLink = event.itemId end
            text:SetText(string.format("Purchased %s for %.2f", itemLink, event.dkp))
         else
            text:SetText(string.format("WARNING! An unknown event of type '%s' was found in your local database!", event.type))
         end
         button:Show()
      else
         button:Hide()
      end
   end
   
end

function Audit:AuditListMouseover(line)
   local dkp = getglobal(line:GetName() .. "DKP")
   local ts = getglobal(line:GetName() .. "Timestamp")
   local desr = getglobal(line:GetName() .. "Description")
   
   GameTooltip:SetOwner(line, "ANCHOR_TOPLEFT", 0, 10)
   GameTooltip:ClearLines()
   GameTooltip:AddDoubleLine(ts:GetText(), dkp:GetText())
   GameTooltip:AddLine(" ")
   GameTooltip:AddLine(desr:GetText(), 1, 1, 1, true)
   GameTooltip:Show()
end